package com.kimguo.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.kimguo.user.model.UserModel;
import com.kimguo.user.service.UserService;

@Component
public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("授权");
		Subject subject = SecurityUtils.getSubject();
		UserModel userModel = (UserModel) subject.getPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.addStringPermission(userModel.getAuthority());
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("认证");
		UsernamePasswordToken user = (UsernamePasswordToken) token;
		UserModel userModel = new UserModel();
		userModel.setUsername(user.getUsername());
		userModel.setPassword(new String(user.getPassword()));
		UserModel model = userService.getByUsernameIsAndPasswordIs(user.getUsername(), new String(user.getPassword()));
	    if (model == null) {
	    	return null;
	    }
	    return new SimpleAuthenticationInfo(model, model.getPassword(), "");
	}
	
}
